<?php
/**
 * GalleryController is used for management of photo.
 * 
 * LBB Solutions Oy 版权所有 © 2013
 */
class GalleryController extends Controller
{
	/**
	 * @return array action filters
	 */
	public function filters() {
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}
	
	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules() {
		return array(
			array('allow', // allow authenticated user to perform below actions
				'users'=>array('@'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}
	
	/**
	 * Give a step guid when there is no profile, tags, default offer picture
	 */
	public function actionIndex()
	{
		//select all photos
		$connection = Yii::app()->db;
		$sql_gallery = 'SELECT g.id, g.url_picture, g.title, g.type, g.id_user, UNIX_TIMESTAMP(g.create_time) AS ts_create_time,
			u.username, u.name
			FROM tbl_merchant_gallery g
			LEFT JOIN tbl_user_account u ON u.id=g.id_user
			WHERE id_merchant=:id_merchant
			ORDER BY create_time DESC';
		$command = $connection->createCommand($sql_gallery);
		$gallery_rows = $command->queryAll(true, array('id_merchant'=>Yii::app()->user->id));
		$connection->active = false;
		
		$this->render('index', array('gallery_rows' => $gallery_rows));
	}
	
	/**
	 * Insert menu picture with AJAX 
	 */
	public function actionUploadGallery()
	{
		//set folder
		$saved_folder = BUtils::GetUploadingFolder(Yii::app()->user->id);
		$url_folder = BUtils::GetUploadingUrl(Yii::app()->user->id);
		
		Yii::import("ext.EAjaxUpload.qqFileUploader");
		$prefix = Yii::app()->request->getParam('prefix', null);
		$allowedExtensions = array("jpg","jpeg","gif","png");
		$sizeLimit = 8 * 1024 * 1024;
		$uploader = new qqFileUploader($allowedExtensions, $sizeLimit);
		$result = $uploader->handleUpload($saved_folder, uniqid($prefix));
		unset($uploader);
		
		//thumb picture
		$thumb = 'thumb_' . $result['filename'];
		//thumb picture 2
		$thumb_200h = 'thumb_200h_' . $result['filename'];
		
		try {
			//resize picture to 640 x 640.
			Yii::import('ext.iwi.Iwi');
			$picture = new Iwi($saved_folder . $result['filename']);
			$minSize = $picture->getMinSize();
			if ($minSize > 640) $minSize = 640;
			$width = $minSize;
			$height = $picture->getRatio() * $width;
			$picture->adaptive($minSize, $height);
			$picture->save($saved_folder . $result['filename']);
			// 120x120
			$picture->adaptive(120, 120);
			$picture->save($saved_folder . $thumb);
			// 283x200
			$picture->adaptive(283, 200);
			$picture->save($saved_folder . $thumb_200h);
			unset($picture);
		} catch (Exception $ex) {
			echo '{"error" : "Photo cannot be saved!"}';
			Yii::app()->end();
		}
		
		//delete the original picture (not delete, just keep them there)
		
		//insert into menu table
		$connection = Yii::app()->db;
		$sql_photo = 'INSERT INTO tbl_merchant_gallery (id_merchant, url_picture, type) VALUES (:id_merchant, :url_picture, 0)';
		$command = $connection->createCommand($sql_photo);
		$command->execute(array('id_merchant'=>Yii::app()->user->id, 'url_picture'=>$url_folder . $thumb));
		
		$command = $connection->createCommand('select id FROM tbl_merchant_gallery WHERE url_picture=:url_picture');
		$row = $command->queryRow(true, array('url_picture'=>$url_folder . $thumb));
		$connection->active = false;
		
		//add id
		if (empty($row['id'])) {
			echo '{"error" : "Photo cannot be saved!"}';
		} else {
			$result['id'] = $row['id'];
			$result['url_picture'] = $url_folder . $result['filename'];
			echo htmlspecialchars(json_encode($result), ENT_NOQUOTES);
		}
	}
	
	/**
	 * Delete photo of gallery.
	 * @param int $id the id of tbl_merchant_gallery.
	 * @throws CHttpException
	 */
	public function actionDeleteGallery($id) {
		if (empty($id)) {
			throw new CHttpException(404, 'The parameter id is missing!');
		}
		
		$sql_delete = 'DELETE FROM tbl_merchant_gallery WHERE id_merchant=:id_merchant AND id=:id';
		$connection = Yii::app()->db;
		$command = $connection->createCommand($sql_delete);
		$command->execute(array('id_merchant'=>Yii::app()->user->id, 'id'=>$id));
		$connection->active = false;

		//delete picture file
		$url_picture = Yii::app()->request->getParam('url');
		if (!empty($url_picture)) {
			//find file name
			$tmp = explode('/', $url_picture);
			$thumbName = array_pop($tmp);
			$uploadPath = $saved_folder = BUtils::GetUploadingFolder(Yii::app()->user->id);
			@unlink($uploadPath . $thumbName);
			$thumbName200 = str_replace('thumb_', 'thumb_200h_', $thumbName);
			@unlink($uploadPath . $thumbName200);
			$fileName = str_replace('thumb_', '', $thumbName);
			@unlink($uploadPath . $fileName);
		}
	}
}